package com.markhsiu.httpserver.event;

import java.io.IOException;
import java.io.OutputStream;

import com.markhsiu.common.memory.ByteBuff;
import com.markhsiu.common.memory.HeapByteBuff;

/**
 * HTTP/1.1 200 OK
 * Server: Apache
 * Content-Type: application/json
 * 
 * data........
 * @author Mark Hsiu
 *
 */
public class Response {

	private OutputStream output;
	private ByteBuff buff = new HeapByteBuff();

	public Response(OutputStream out) {
		output = out;
	}
	

	public void send() throws IOException {
		System.out.println("..... send  length "+buff.length());
		if (buff.length() == 0) {
			System.out.println(" ..... not find ..... ");
			output.write(getNotFind().getBytes());
		} else {
			output.write(getHeaders().getBytes());
			output.write(buff.data());
		}
		
		output.flush();
	}

	public void write(byte[] bytes) throws IOException {
		buff.put(bytes);
	}
	
	public void write(byte[] bytes, int offset, int length) throws IOException {
		buff.put(bytes,offset,length);
	}

	private String getHeaders(){
		StringBuilder message = new StringBuilder();
		message.append("HTTP/1.1 200 OK\r\n");
		message.append("Cache-Control: no-cache\r\n");
		message.append("Content-Type: text/html; charset=utf-8\r\n");
		message.append("Content-Length: "+buff.length()+"\r\n");
		message.append("\r\n");
		return message.toString();
	}
	
	public String getError() {
		StringBuilder errorMessage = new StringBuilder();
		errorMessage.append("HTTP/1.1 500 System Error\r\n");
		errorMessage.append("Content-Type: text/plain; charset=utf-8\r\n");
		errorMessage.append("Content-Length: 21\r\n");
		errorMessage.append("\r\n");
		errorMessage.append("<h1>System Error</h1>");
		errorMessage.append("");
		
		return errorMessage.toString();
	}
	
	public String getNotFind() {
		StringBuilder errorMessage = new StringBuilder();
		errorMessage.append("HTTP/1.1 404 File Not Found\r\n");
		errorMessage.append("Content-Type: text/plain; charset=utf-8\r\n");
		errorMessage.append("Content-Length: 23\r\n");
		errorMessage.append("\r\n");
		errorMessage.append("<h1>File Not Found</h1>");
		errorMessage.append("");
		
		return errorMessage.toString();
	}
	
	public String getSuccess() {
		StringBuilder errorMessage = new StringBuilder();
		errorMessage.append("HTTP/1.1 200 OK\r\n");
		errorMessage.append("Content-Type: text/plain; charset=utf-8\r\n");
		errorMessage.append("Content-Length: 16\r\n");
		errorMessage.append("\r\n");
		errorMessage.append("<h1>SUCCESS</h1>");
		errorMessage.append("");
		
		return errorMessage.toString();
	}
}
